﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using CosyTrade.Data;
using CosyTrade.Store;
using CosyTrade.UI;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using NHibernate.Expression;
using CosyTrade.ClientForm.Properties;
using CosyTrade.ClientForm.Printer;
using CosyTrade.Financial;

namespace CosyTrade.ClientForm.Store
{
    public partial class ProductManagerForm : FormBase
    {
        private Image headimage;
        private Image bodyimage;
        private Font captionFont;
        private Color captionColor;
        private bool paintCaption;
        
        public ProductManagerForm()
        {
            InitializeComponent();
        }

        protected override void InitCommandBar()
        {
            ToolbarItems.AddCommandItem(new ToolbarCommandItem("CreateProduct", Resources.add, "新建商品", true, true, true,
                                                               CreateNewCallback));

            ToolbarItems.AddCommandItem(new ToolbarCommandItem("ModifyProduct", Resources.table_edit, "修改商品", true, true, true,
                                                               ModifyCallback));

            ToolbarItems.AddCommandItem(new ToolbarCommandItem("DeleteProduct", Resources.delete, "删除商品", true, true, true,
                                                               DeleteCallback));
            //ToolbarItems.AddCommandItem(new ToolbarCommandItem("setProductImglist", Properties.Resources.picture, "相簿封面与背景", true, true, true,
            //                                       TemplateSettingCallBack));
            //ToolbarItems.AddCommandItem(new ToolbarCommandItem("PrintProductimglist", Properties.Resources.printer, "打印相簿", true, true, true,
            //                                                   PrintCategoryBookCallback));
            ToolbarItems.AddCommandItem(new ToolbarCommandItem("PrinterClient", Properties.Resources.printer, "打印商品资料", true, true, true, delegate { PrinterReport(); }));

            ToolbarItems.AddCommandItem(new ToolbarCommandItem("CloseForm", Resources.door_out, "关闭", true, true, true,
                                                               CloseCallback));
        }

        PrintProducts pps = new PrintProducts();

        void PrinterReport()
        {
            if(pps!=null) pps.ShowDialog();
        }

        private void TemplateSettingCallBack(object sender, EventArgs e)
        {
            CategoryBookPageSeting setting = new CategoryBookPageSeting();
            setting.ShowDialog();
            headimage = setting.HeadImage;
            bodyimage = setting.BodyImage;
            captionColor = setting.CaptionColor;
            captionFont = setting.CaptionFont;
            paintCaption = setting.PaintCaption;
        }

        private void PrintCategoryBookCallback(object sender, EventArgs e)
        {
            if (bindingSource1.DataSource == null) return;
            IList<Product> sources = bindingSource1.DataSource as IList<Product>;
            if (sources.Count==0)
            {
                Functions.ShowMessageBox("没有商品记录");
                return;
            }
            IList<CategoryBookItem> bookitems = new List<CategoryBookItem>();


            foreach (Product item in sources)
                {

                    CompanyProductView view = new CompanyProductView();
                    CosyTrade.Store.CompanyStore come = Operation.StoreManager.GetCompanyStore(GlobalInfo.CurrentCompany.PrimaryKey,item.PrimaryKey); 
                    if(come==null){
                        come = new CosyTrade.Store.CompanyStore();
                        come.BookCount=0;
                        come.Company = GlobalInfo.CurrentCompany;
                        come.Products=item;
                    }

                    ProductPrice pp = new ProductPrice();
                    pp.Price = 0; ;
                    pp.CompanyStore =come;
                    pp.ShortCode = "";

                    view.OnCompany = GlobalInfo.CurrentCompany;
                    view.PackageCount = 0;
                    view.PackageUnitCount = 0;
                    view.Price = pp;
                    view.Store = come;
                    view.OnCompany = GlobalInfo.CurrentCompany;
                    view.TotalBulk = "";
                    view.TotalWeight = 0;

                    CategoryBookItem books = new CategoryBookItem();
                    books.OrderKey = 0;
                    books.ProductView = view;
                    bookitems.Add(books);
            }

            if (headimage == null || bodyimage == null)
                TemplateSettingCallBack(null, null);
            if (headimage == null) headimage = Properties.Resources.lifenghead;
            if (bodyimage == null) bodyimage = Properties.Resources.lifenglist;

            PrintProduct print = new PrintProduct();
            print.BodyImage = bodyimage;
            print.HeadImage = headimage;
            print.DataStorage = Operation.DataStorage;
            IList<ExchangeRate> rates = Operation.FinancialSystem.GetExchangeRateList(GlobalInfo.CurrentCompany.PrimaryKey);
            print.Exchange = rates.Count>0?rates[0]:new ExchangeRate();

            print.PaintCaption = paintCaption;
            print.CaptionFont = captionFont;
            print.CaptionColor = captionColor;
            print.CompanyName = GlobalInfo.CurrentCompany.Caption;
            print.DrawchangdaProducts(bookitems, GlobalInfo.CurrentCompany);
        }
        
        private void CreateNewCallback(object sender, EventArgs e)
        {
            ProductDetailForm detailForm = new ProductDetailForm();
            detailForm.Show();
        }

        private void ModifyCallback(object sender, EventArgs e)
        {
            ModifyCurrentObj(true);
        }

        private void DeleteCallback(object sender, EventArgs e)
        {
            if (bindingSource1.Current == null)
            {
                Functions.ShowMessageBox("请选择要删除的商品");
                return;
            }
            
            Product curr = bindingSource1.Current as Product;
            if (curr == null) return;

            if (Functions.ShowConfigBox("是否删除该商品？") != DialogResult.Yes) return;

            Operation.ProductManager.DeleteProduct(curr.PrimaryKey);
            bindingSource1.RemoveCurrent();
        }

        private void CloseCallback(object sender, EventArgs e)
        {
            Close();
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if(e.Value is ProductCategoryBase)
            {
                e.DisplayText = string.Format("{0} - {1}", ((ProductCategoryBase) e.Value).CategoryChinese,
                                              ((ProductCategoryBase) e.Value).CategorySpanish);
            }
        }

        private void productCategoryDropdownControl1_ValueSelected(object sender, EventArgs e)
        {
            popupContainerEdit1.EditValue = productCategoryDropdownControl1.SelectedProductCategory;
            popupContainerEdit1.ClosePopup();
        }

        private void popupContainerEdit1_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if(e.Value as ProductCategoryBase != null)
            {
                e.DisplayText = string.Format("{0} - {1}", ((ProductCategoryBase) e.Value).CategoryChinese,
                                              ((ProductCategoryBase) e.Value).CategorySpanish);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (Functions.ValueIsEmpty(txtBarcode) && Functions.ValueIsEmpty(txtChinese) && Functions.ValueIsEmpty(txtSpanish) && popupContainerEdit1.EditValue == null)
            {
                Functions.ShowMessageBox("至少输入一个搜索条件");
                return;
            }

            Queue<ICriterion> criLst = new Queue<ICriterion>();
            if (!Functions.ValueIsEmpty(txtBarcode))
                criLst.Enqueue(Expression.Like("BarCode", Functions.GetSearchString(txtBarcode.Text),MatchMode.Anywhere));
            if (!Functions.ValueIsEmpty(txtChinese))
                criLst.Enqueue(Expression.Like("CaptionChinese", Functions.GetSearchString(txtChinese.Text),MatchMode.Anywhere));
            if (!Functions.ValueIsEmpty(txtSpanish))
                criLst.Enqueue(Expression.Like("CaptionSpaish", Functions.GetSearchString(txtSpanish.Text),MatchMode.Anywhere));
            if (popupContainerEdit1.EditValue != null)
                criLst.Enqueue(Expression.Eq("Category", popupContainerEdit1.EditValue));
            if (!Functions.ValueIsEmpty(txtProdCode))
                criLst.Enqueue(Expression.Like("ProductCode", Functions.GetSearchString(txtProdCode.Text), MatchMode.Anywhere));

            ICriterion criterion = DataHelper.BuildCriterionByAnd(criLst);
            IList<Product> dataSource = Operation.ProductManager.SearchProductList(criterion, int.MaxValue);
            bindingSource1.DataSource = new List<Product>(dataSource);
            pps.ProductSources = dataSource;
        }

        private void ModifyCurrentObj(bool showNodataErr)
        {
            if(bindingSource1.Current == null)
            {
                if (showNodataErr) Functions.ShowMessageBox("请选择要修改的商品");
                return;
            }

            Product curr = bindingSource1.Current as Product;
            if (curr == null) return;

            ProductDetailForm detailForm = new ProductDetailForm(curr.PrimaryKey);
            detailForm.Show();
        }

        private void gridView1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) ModifyCurrentObj(false);
        }

        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks <= 1 || e.Button != MouseButtons.Left) return;
            GridHitInfo hitInfo = gridView1.CalcHitInfo(e.Location);
            if (hitInfo.InRow) ModifyCurrentObj(false);
        }

        private void gridControl1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks > 1 && e.Button == System.Windows.Forms.MouseButtons.Left) 
                ShowImage();
        }

        void ShowImage()
        {
            if (bindingSource1.Current == null) return;
            Product product = bindingSource1.Current as Product;
            if (product == null) return;
            ImageSee imageSee = new ImageSee();
            byte[] imgData = Operation.DataStorage.GetData(product.ImagePath);
            if (imgData == null) return;
            imageSee.ShowImage = new Bitmap(new MemoryStream(imgData));
            imageSee.ShowDialog();
        }

        private void btnSearch2_Click(object sender, EventArgs e)
        {
            ICriterion criterion = Expression.Or(Expression.Like("ProductCode", Functions.GetSearchString(txtKeyword.Text), MatchMode.Anywhere), Expression.Like("BarCode", Functions.GetSearchString(txtKeyword.Text), MatchMode.Anywhere));
            criterion = Expression.Or(criterion, Expression.Like("FactoryModule", Functions.GetSearchString(txtKeyword.Text), MatchMode.Anywhere));
            criterion = Expression.Or(criterion, Expression.Like("ModuleInfo", Functions.GetSearchString(txtKeyword.Text), MatchMode.Anywhere));
            criterion = Expression.Or(criterion, Expression.Like("Material", Functions.GetSearchString(txtKeyword.Text), MatchMode.Anywhere));
            criterion = Expression.Or(criterion, Expression.Like("CaptionChinese", Functions.GetSearchString(txtKeyword.Text), MatchMode.Anywhere));
            criterion = Expression.Or(criterion, Expression.Like("CaptionSpaish", Functions.GetSearchString(txtKeyword.Text), MatchMode.Anywhere));
            criterion = Expression.Or(criterion, Expression.Like("Bulk", Functions.GetSearchString(txtKeyword.Text), MatchMode.Anywhere));

            IList<Product> dataSource = Operation.ProductManager.SearchProductList(criterion, int.MaxValue);
            if (dataSource != null)
            {
                bindingSource1.DataSource = new List<Product>(dataSource);
                pps.ProductSources = dataSource;
            }
        }
    }
}
